package site.marqstree.kotlin.library.base.ui.util

import androidx.fragment.app.FragmentActivity
import cn.pedant.SweetAlert.SweetAlertDialog
import com.blankj.utilcode.util.AppUtils
import site.marqstree.kotlin.library.base.data.net.request.RxRequest
import site.marqstree.kotlin.library.base.data.bean.update.CommonUpdateBean
import site.marqstree.kotlin.library.base.extent.json2Bean
import site.marqstree.kotlin.library.base.data.net.observer.RxObserver
import site.marqstree.kotlin.library.base.ui.dialog.update.DialogUpdate


/*
 * 项目名: KotlinMall
 * 包名: site.marqstree.kotlin.library.base.ui.util
 * 文件名: UpdateAppUtils
 * 创建者: marqstree
 * 创建时间: 2020/3/3 10:34
 * 描述:
 * //检查升级
    //demo:
    //UpdateAppUtil().requestUpdate(activity!!,Constant.APP_UPDATE_URL)
 */
class UpdateAppUtil {

    fun requestUpdate(activity: FragmentActivity,
                      updateVersionUrl: String){
        RxRequest.builder()
            .setContext(activity)
            .setUrl(updateVersionUrl)
            .get()
            .json2Bean(CommonUpdateBean::class.java)
            .subscribe(object : RxObserver<CommonUpdateBean>(){
                override fun onNext(data: CommonUpdateBean) {
                    //通过版本号检查是否需要升级
                    if(isNeedUpdate(data)) {
                        //弹出升级对话框
                        DialogUpdate().show(
                            activity,
                            data
                        )
                    }
                }

                override fun onError(e: Throwable) {
                    SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("糟糕...")
                        .setContentText("更新失败了!")
                        .show()
                }
            })
    }

    //判断是否需要升级
    //比较本地和后台版本号
    private fun isNeedUpdate(updateBean: CommonUpdateBean):Boolean{
        val appVersionCode = AppUtils.getAppVersionCode()
        return appVersionCode<updateBean.versionCode
    }
}